package com.handyshop.mall.user.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.handyshop.mall.basic.core.constants.BaseConstants;
import com.handyshop.mall.dubbo.user.entity.SysRole;
import com.handyshop.mall.dubbo.user.entity.SysUserRole;
import com.handyshop.mall.user.mapper.SysRoleMapper;
import com.handyshop.mall.user.service.SysRoleService;
import com.handyshop.mall.user.service.SysUserRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    private final SysUserRoleService sysUserRoleService;

    /**
     * 根据用户id获取角色
     *
     * @param userId 用户id
     * @return 角色
     */
    @Override
    public List<SysRole> findByUserId(Long userId) {
        // 获取角色
        LambdaQueryWrapper<SysUserRole> sysUserRoleWrapper = new LambdaQueryWrapper<>();
        sysUserRoleWrapper.eq(SysUserRole::getUserId, userId);
        List<SysUserRole> sysUserRoles = sysUserRoleService.list(sysUserRoleWrapper);
        if (CollUtil.isEmpty(sysUserRoles)) {
            return new ArrayList<>();
        }
        List<Long> roleIds = sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        LambdaQueryWrapper<SysRole> sysRoleWrapper = new LambdaQueryWrapper<>();
        sysRoleWrapper.in(SysRole::getId, roleIds).eq(SysRole::getDeleteFlag, BaseConstants.NOT_DELETE_FLAG);
        return this.list(sysRoleWrapper);
    }

}
